package com.ruoyi.system.controller;

import java.util.List;
import java.io.IOException;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.constant.ActivityConstant;
import com.ruoyi.common.core.constant.ApproveConstant;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.RegExUtil;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.annotation.Logical;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.domain.Activity;
import com.ruoyi.system.domain.SchoolRole;
import com.ruoyi.system.domain.vo.ApproveVo;
import com.ruoyi.system.service.*;
import jdk.nashorn.api.scripting.ScriptUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.domain.ApproveLog;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 审批记录Controller
 * 
 * @author hyb
 * @date 2023-02-06
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("/approveLog")
public class ApproveLogController extends BaseController
{
    @Autowired
    private IApproveLogService approveLogService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private ISchoolRoleService schoolRoleService;

    @Autowired
    ISysDeptService deptService;



    /**
     * 查询审批记录列表
     */
    @RequiresPermissions("approve:approveLog:list")
    @GetMapping("/list")
    public TableDataInfo list(ApproveLog approveLog)
    {
        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setUserId(SecurityUtils.getUserId());
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(schoolRole);
        if (schoolRoles.size()==0){
            throw new GlobalException("该账号未认证学校信息无法审批!");
        }
        schoolRole=schoolRoles.get(0);
        //只查自己作为上级部门该审批的记录
        approveLog.setPf3(String.valueOf(schoolRole.getDeptId()));
        //自己能看见自己报审的记录
        approveLog.setToApproveUserId(SecurityUtils.getUserId());
        startPage();
        List<ApproveLog> list = approveLogService.selectApproveLogpf2orpf3(approveLog);
        return getDataTable(list);
    }

    /**
     * 导出审批记录列表
     */
    @RequiresPermissions("approve:approveLog:export")
    @Log(title = "审批记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ApproveLog approveLog)
    {

        List<ApproveLog> list = approveLogService.selectApproveLogList(approveLog);
        ExcelUtil<ApproveLog> util = new ExcelUtil<ApproveLog>(ApproveLog.class);
        util.exportExcel(response, list, "审批记录数据");
    }

    /**
     * 获取审批记录详细信息
     */
    @RequiresPermissions("approve:approveLog:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(approveLogService.selectApproveLogById(id));
    }

    /**
     * 新增审批记录
     */
    @RequiresPermissions("approve:approveLog:add")
    @Log(title = "审批记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ApproveLog approveLog) throws Exception {
        return toAjax(approveLogService.insertApproveLog(approveLog));
    }

    //审批
    @RequiresPermissions("approve:approveLog:sendApprove")
    @Log(title = "更新审批",businessType = BusinessType.INSERT)
    @PostMapping("/sendApprove")
    /*
    * TODO:
    *  1. 先认证账号信息
    *  2. 检查活动状态(报审中,院审中)
    *  3. 判断审批意见approveVo
    *
    * */
    public AjaxResult sendApprove(@RequestBody ApproveVo approveVo){

        if (!RegExUtil.isNumber(approveVo.getId()) && !RegExUtil.isNumber(approveVo.getApproveId())){
            return AjaxResult.error("id必须是数字");
        }
        //查询账号是否有school_role信息
        Long userId = SecurityUtils.getUserId();
        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setUserId(userId);
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(schoolRole);
        if (schoolRoles.size()==0){
            return AjaxResult.error("该账号还未认证学校信息,无法审批!");
        }

        schoolRole=schoolRoles.get(0);

        //查询该活动的本身状态
        Activity activity = activityService.selectActivityById(Long.parseLong(approveVo.getId()));

        if (activity==null){
            return AjaxResult.error("审核活动不存在!");
        }

        //必须在报审中(第一次报审,或者第二次院里报审)
        if (!activity.getStatus().equals(ActivityConstant.TO_APPROVE_STATUS)
        &&!activity.getStatus().equals(ActivityConstant.SCHOOL_APPROVE)
        ){
            return AjaxResult.error("该活动不在待审核中,无法审核!");
        }


        //这条记录是否被审核过了,审核过了就是判断approve_id这些属性是否为空
        ApproveLog log = approveLogService.selectApproveLogById(Long.parseLong(approveVo.getApproveId()));
        if (log==null){
            return AjaxResult.error("该活动未报审!");
        }
        if (log.getApproveUserId()!=null){
            return AjaxResult.error("该活动已经审核过了!");
        }
        //判断该活动是否是自己审核的
        if (!log.getPf3().equals(String.valueOf(schoolRole.getDeptId()))){
            return AjaxResult.error("该活动非自己审核!");
        }

        //避免伪造信息
        if (!log.getActivityId().equals(activity.getId())){
            return AjaxResult.error("活动id与审批记录不对应!");
        }

        ApproveLog approveLog = new ApproveLog();
        //同时记录自己的信息
//        approveLog.setApproveCount(log.getApproveCount()+1);
        approveLog.setApproveUserId(SecurityUtils.getUserId());
        approveLog.setApproveMail(schoolRole.getEmail());
        approveLog.setApproveName(schoolRole.getName());
        approveLog.setApproveNote(approveVo.getApproveNote());

        //如果前端传来审批通过
        if (ApproveConstant.success.equals(approveVo.getStatus())){
             //判断是校级活动还是院级活动
            if (activity.getLevel().equals(ActivityConstant.LEVEL_0)){
                //如果还在报审中,说明此刻是院审核
                if (activity.getStatus().equals(ActivityConstant.TO_APPROVE_STATUS)){
                    //设置为院审完成
                    approveLog.setStatus(ApproveConstant.COLLAGE_STATUS);
                }else{
                    //设置校审完成
                    approveLog.setStatus(ApproveConstant.APPROVE_FINAL);
                }
            }else{
                //设置校审完成
                approveLog.setStatus(ApproveConstant.APPROVE_FINAL);
            }

        }else{
            //设置驳回
            approveLog.setStatus(ApproveConstant.APPROVE_REJECT);
        }
        //设置审批时间
        approveLog.setApproveTime(DateUtils.getNowDate());


        //更新approvelog表和activity表
        //通过活动id和pf3去更新对应的报审记录


        try{
            approveLog.setId(Long.parseLong(approveVo.getApproveId()));
            approveLog.setActivityId(Long.parseLong(approveVo.getId()));
            approveLog.setPf3(String.valueOf(schoolRole.getDeptId()));
            Activity activityr = new Activity();
            activityr.setId(activity.getId());
            activityr.setStatus(approveLog.getStatus());

            activityService.updateActivity(activityr);


            approveLogService.updateApproveLogByActivityIdAndPf3(approveLog);

        }catch (Exception e){
            throw new GlobalException("未知异常!");
        }

        return AjaxResult.success();
    }

    @RequiresPermissions(value = {"approve:approveLog:toApprove","approve:approveLog:toReApprove"},logical = Logical.OR)
    @Log(title = "新增报审",businessType = BusinessType.INSERT)
    @PostMapping("/send")
    public AjaxResult send(@RequestParam("id")String id,@RequestParam(value = "approveId",required = false)String approveId) throws Exception {

        if (!RegExUtil.isNumber(id)){
            return AjaxResult.error("id必须为数字");
        }
        //查询审批的活动是否存在
        Activity activity = activityService.selectActivityById(Long.parseLong(id));
        if (activity==null){
            return AjaxResult.error("审批活动不存在!");
        }else{
            //状态是否为刚创建或者驳回或者院审中(2)
            if (!Objects.equals(activity.getStatus(), ActivityConstant.CREATE_STATUS)
                    &&! Objects.equals(activity.getStatus(),ActivityConstant.APPROVE_REJECT)
                            &&! Objects.equals(activity.getStatus(),ActivityConstant.COLLAGE_STATUS)

            ){
                return AjaxResult.error("该活动非刚创建/已驳回,无法报审!");
            }
        }
        //查询报审人的schoolrole信息
        Long userId = SecurityUtils.getUserId();
        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setUserId(userId);
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(schoolRole);
        if (schoolRoles.size()==0){
            return AjaxResult.error("该账号还未认证学校信息!");
        }

        ApproveLog approveLog = new ApproveLog();
        //拿取第一个信息,多余的不要,一个账号只能认证一个
        SchoolRole role = schoolRoles.get(0);
        approveLog.setToApproveMail(role.getEmail());
        approveLog.setToApproveName(role.getName());
        approveLog.setToApprovePhone(role.getPhone());

        approveLog.setToApproveUserId(userId);
        approveLog.setToApproveTime(DateUtils.getNowDate());
        approveLog.setApproveCount(0L);
        approveLog.setActivityId(activity.getId());
        approveLog.setPf1(activity.getName());
        approveLog.setStatus(ApproveConstant.CREATE_STATUS);
        //设置自己的部门id
        approveLog.setPf2(String.valueOf(role.getDeptId()));

        //设置到底由谁来审核这个活动
        //先判断是院级活动还是校级活动
        if (activity.getLevel().equals(ActivityConstant.LEVEL_0)){
            //如果是院级活动pf3设置为自己,表示先让自己的学院来审核
            approveLog.setPf3(String.valueOf(role.getDeptId()));
        }else{
            //如果是校级活动,设置pf3为自己部门的上级
            SysDept sysDept = deptService.selectDeptById(role.getDeptId());
            Long parentId = sysDept.getParentId();
            //如果自己没有上级部门,说明是校级账号,直接让自己同部门的人来审核
            if (parentId==null){
                parentId=role.getDeptId();
            }
            approveLog.setPf3(String.valueOf(parentId));
        }
        //还有一种可能,如果是院审核了,要上报给学校,这个时候直接判断活动的状态就可以了
        //如果活动状态为2,也就是院审核完了
        if (activity.getStatus().equals(ActivityConstant.COLLAGE_STATUS)){

            SysDept sysDept = deptService.selectDeptById(role.getDeptId());
            Long parentId = sysDept.getParentId();
            if (parentId==null){
                return AjaxResult.error("该账号没有上级部门,无法再次报审,请联系管理员解决!");
            }
            approveLog.setStatus(ApproveConstant.SCHOOL_APPROVE);
            approveLog.setPf3(String.valueOf(parentId));
        }


        try {
            approveLogService.insertApproveLog(approveLog);

            //修改活动状态
            Activity activityr = new Activity();
            activityr.setId(Long.parseLong(id));
            activityr.setStatus(approveLog.getStatus());

            activityService.updateActivity(activityr);


            //如果approveId不为空,说明是院级审核完毕后再报审,这个时候要修改原来审批记录的状态
            if (!StringUtils.isEmpty(approveId)){
                if (!RegExUtil.isNumber(approveId)){
                    return AjaxResult.error("approveId必须是数字");
                }
                ApproveLog log = new ApproveLog();
                log.setId(Long.parseLong(approveId));
                log.setStatus(ApproveConstant.THIS_FINAL);
                approveLogService.updateApproveLog(log);
            }
        }catch (Exception e){
            return AjaxResult.error("未知异常!");
        }



        return AjaxResult.success();
    }

    /**
     * 修改审批记录
     */
    @RequiresPermissions("approve:approveLog:edit")
    @Log(title = "审批记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ApproveLog approveLog)
    {
        return toAjax(approveLogService.updateApproveLog(approveLog));
    }

    /**
     * 删除审批记录
     */
    @RequiresPermissions("approve:approveLog:remove")
    @Log(title = "审批记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(approveLogService.deleteApproveLogByIds(ids));
    }
}
